#!/usr/bin/env node

const { validateProbabilities, calculateEntropy } = require('./entropyUtils');

const probabilities = process.argv.slice(2);

if (probabilities.length === 0) {
  interactiveMode();
} else {
  if (!validateProbabilities(probabilities, true)) {
    if (probabilities.length < 2) {
      console.log('命令行参数错误：概率数据少于两个!');
    } else if (/,/.test(probabilities.join('')) && /\s/.test(probabilities.join(''))) {
      console.log('命令行参数错误：不能同时使用逗号和空格分隔概率!');
    } else {
      console.log('命令行参数错误：请输入有效的信源概率分布，概率值必须在0和1之间，且总和为1。');
    }
  } else {
    console.log(`p=[${probabilities.join(', ')}]`);
    console.log(`h(p)= ${calculateEntropy(probabilities)} bit`);
  }
}

function interactiveMode() {
  const readline = require('readline');
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  console.log('请输入信源概率分布：（Ctrl+D 退出输入）');
  let probabilities = [];
  let index = 0;

  function askProbability() {
    rl.question(`p${index}: `, (input) => {
      if (input.trim() === '') {
        if (probabilities.length < 2) {
          console.log('错误：概率数据少于两个！');
          askProbability();
        } else {
          validateAndCalculate(probabilities);
        }
      } else {
        const prob = parseFloat(input);
        if (isNaN(prob)) {
          console.log('错误：请输入有效的数字！');
        } else if (prob <= 0 || prob >= 1) {
          console.log('错误：概率值必须在0和1之间！');
        } else {
          probabilities.push(prob);
          index++;
        }
        askProbability();
      }
    });
  }

  function validateAndCalculate(probs) {
    const sum = probs.reduce((acc, val) => acc + val, 0);
    if (Math.abs(sum - 1) <= 1e-10) {
      console.log(`p=[${probs.join(', ')}]`);
      console.log(`h(p)= ${calculateEntropy(probs)} bit`);
      rl.close();
      process.exit(0);
    } else {
      console.log(`错误：概率之和不等于1（当前和为${sum.toFixed(10)}）！`);
      askProbability();
    }
  }

  askProbability();
}